import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_test_robots/src/keyboard.dart'; // 请替换为实际路径
import 'dart:io';

void main() {
  final platform = Platform.operatingSystem;
  print('=== start keyboard test, platform is: $platform ===');
  group('KeyboardInput Extension Tests', () {
    // 辅助方法：将 LogicalKeyboardKey 转换为字符
    String? _keyToCharacter(LogicalKeyboardKey key, bool isShiftPressed) {
      // 使用 keyLabel 进行映射
      final keyLabel = key.keyLabel;

      final letterMap = {
        'A': isShiftPressed ? 'A' : 'a',
        'B': isShiftPressed ? 'B' : 'b',
        'C': isShiftPressed ? 'C' : 'c',
        'D': isShiftPressed ? 'D' : 'd',
        'E': isShiftPressed ? 'E' : 'e',
        'F': isShiftPressed ? 'F' : 'f',
        'G': isShiftPressed ? 'G' : 'g',
        'H': isShiftPressed ? 'H' : 'h',
        'I': isShiftPressed ? 'I' : 'i',
        'J': isShiftPressed ? 'J' : 'j',
        'K': isShiftPressed ? 'K' : 'k',
        'L': isShiftPressed ? 'L' : 'l',
        'M': isShiftPressed ? 'M' : 'm',
        'N': isShiftPressed ? 'N' : 'n',
        'O': isShiftPressed ? 'O' : 'o',
        'P': isShiftPressed ? 'P' : 'p',
        'Q': isShiftPressed ? 'Q' : 'q',
        'R': isShiftPressed ? 'R' : 'r',
        'S': isShiftPressed ? 'S' : 's',
        'T': isShiftPressed ? 'T' : 't',
        'U': isShiftPressed ? 'U' : 'u',
        'V': isShiftPressed ? 'V' : 'v',
        'W': isShiftPressed ? 'W' : 'w',
        'X': isShiftPressed ? 'X' : 'x',
        'Y': isShiftPressed ? 'Y' : 'y',
        'Z': isShiftPressed ? 'Z' : 'z',
      };

      // 数字键映射
      final numberMap = {
        '0': isShiftPressed ? ')' : '0',
        '1': isShiftPressed ? '!' : '1',
        '2': isShiftPressed ? '@' : '2',
        '3': isShiftPressed ? '#' : '3',
        '4': isShiftPressed ? '\$' : '4',
        '5': isShiftPressed ? '%' : '5',
        '6': isShiftPressed ? '^' : '6',
        '7': isShiftPressed ? '&' : '7',
        '8': isShiftPressed ? '*' : '8',
        '9': isShiftPressed ? '(' : '9',
      };

      // 符号键映射
      final symbolMap = {
        ' ': ' ',
        '-': isShiftPressed ? '_' : '-',
        '=': isShiftPressed ? '+' : '=',
        '[': isShiftPressed ? '{' : '[',
        ']': isShiftPressed ? '}' : ']',
        '\\': isShiftPressed ? '|' : '\\',
        ';': isShiftPressed ? ':' : ';',
        '\'': isShiftPressed ? '"' : '\'',
        ',': isShiftPressed ? '<' : ',',
        '.': isShiftPressed ? '>' : '.',
        '/': isShiftPressed ? '?' : '/',
        '`': isShiftPressed ? '~' : '`',
        '!': '!',
        '@': '@',
        '#': '#',
        '\$': '\$',
        '%': '%',
        '^': '^',
        '&': '&',
        '*': '*',
        '(': '(',
        ')': ')',
        '_': '_',
        '+': '+',
        '{': '{',
        '}': '}',
        '|': '|',
        ':': ':',
        '"': '"',
        '<': '<',
        '>': '>',
        '?': '?',
        '~': '~',
      };

      // 首先检查字母映射
      if (letterMap.containsKey(keyLabel)) {
        return letterMap[keyLabel];
      }
      
      // 然后检查数字映射
      if (numberMap.containsKey(keyLabel)) {
        return numberMap[keyLabel];
      }
      
      // 最后检查符号映射
      if (symbolMap.containsKey(keyLabel)) {
        return symbolMap[keyLabel];
      }

      // 如果 keyLabel 是单个字符但不在映射表中，直接返回
      if (keyLabel.length == 1) {
        print('Using keyLabel as fallback: "$keyLabel"');
        return keyLabel;
      }

      print('Unmapped key: $key, keyId: ${key.keyId}, keyLabel: "$keyLabel"');
      return null;
    }

    testWidgets('typeKeyboardText should type characters correctly', (WidgetTester tester) async {
      final textFieldKey = UniqueKey();
      String enteredText = '';
      
      // 为 RawKeyboardListener 和 TextField 分别创建不同的 FocusNode
      final rawKeyboardFocusNode = FocusNode();
      final textFieldFocusNode = FocusNode();
  
      // 创建一个自定义的文本输入控件，能够响应物理键盘事件
      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: KeyboardListener(
              focusNode: rawKeyboardFocusNode,
              onKeyEvent: (event) {
                if (event is KeyDownEvent) {
                  // 将键盘事件转换为文本
                  final isShiftPressed = HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft) ||
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight) || 
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shift);
                  final character = _keyToCharacter(event.logicalKey, isShiftPressed);
                  print('Key: ${event.logicalKey}, Shift: $isShiftPressed, Character: $character');
                  if (character != null) {
                    enteredText += character;
                  }
                }
              },
              child: TextField(
                key: textFieldKey,
                focusNode: textFieldFocusNode,
                // readOnly: true, // 设置为只读，因为我们通过键盘事件处理输入
                controller: TextEditingController(text: enteredText),
              ),
            ),
          ),
        ),
      );

      // 确保文本框获得焦点
      rawKeyboardFocusNode.requestFocus();
      await tester.pump();
  
      // 使用 typeKeyboardText 方法输入文本
      await tester.typeKeyboardText('Hello123 -=[];,./');
  
      // 等待所有字符输入完成
      await tester.pumpAndSettle();
  
      // 验证输入的文本是否正确
      expect(enteredText, equals('Hello123 -=[];,./'));
    });

    testWidgets('typeKeyboardText should handle special characters', (WidgetTester tester) async {
      final textFieldKey = UniqueKey();
      String enteredText = '';
      
      // 为 RawKeyboardListener 和 TextField 分别创建不同的 FocusNode
      final rawKeyboardFocusNode = FocusNode();
      final textFieldFocusNode = FocusNode();
  
      // 创建一个自定义的文本输入控件，能够响应物理键盘事件
      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: KeyboardListener(
              focusNode: rawKeyboardFocusNode,
              onKeyEvent: (event) {
                if (event is KeyDownEvent) {
                  // 将键盘事件转换为文本
                  final isShiftPressed = HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft) ||
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight) || 
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shift);
                  final character = _keyToCharacter(event.logicalKey, isShiftPressed);
                  print('Key: ${event.logicalKey}, Shift: $isShiftPressed, Character: $character');
                  if (character != null) {
                    enteredText += character;
                  }
                }
              },
              child: TextField(
                key: textFieldKey,
                focusNode: textFieldFocusNode,
                // readOnly: true, // 设置为只读，因为我们通过键盘事件处理输入
                controller: TextEditingController(text: enteredText),
              ),
            ),
          ),
        ),
      );

      // 确保文本框获得焦点
      rawKeyboardFocusNode.requestFocus();
      await tester.pump();
  
      // 使用 typeKeyboardText 方法输入文本
      await tester.typeKeyboardText('Test!@#%^&*()_+{}:|<>?');
  
      // 等待所有字符输入完成
      await tester.pumpAndSettle();
  
      // 验证输入的文本是否正确
      expect(enteredText, equals('Test!@#%^&*()_+{}:|<>?'));
    });

    testWidgets('typeKeyboardText should handle empty string', (WidgetTester tester) async {
      final textFieldKey = UniqueKey();
      String enteredText = 'input text is empty.';
      
      // 为 RawKeyboardListener 和 TextField 分别创建不同的 FocusNode
      final rawKeyboardFocusNode = FocusNode();
      final textFieldFocusNode = FocusNode();
  
      // 创建一个自定义的文本输入控件，能够响应物理键盘事件
      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: KeyboardListener(
              focusNode: rawKeyboardFocusNode,
              onKeyEvent: (event) {
                if (event is KeyDownEvent) {
                  // 将键盘事件转换为文本
                  final isShiftPressed = HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft) ||
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight)|| 
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shift);
                  final character = _keyToCharacter(event.logicalKey, isShiftPressed);
                  print('Key: ${event.logicalKey}, Shift: $isShiftPressed, Character: $character');
                  if (character != null) {
                    enteredText += character;
                  }
                }
              },
              child: TextField(
                key: textFieldKey,
                focusNode: textFieldFocusNode,
                // readOnly: true, // 设置为只读，因为我们通过键盘事件处理输入
                controller: TextEditingController(text: enteredText),
              ),
            ),
          ),
        ),
      );

      // 确保文本框获得焦点
      rawKeyboardFocusNode.requestFocus();
      await tester.pump();
  
      // 使用 typeKeyboardText 方法输入文本
      await tester.typeKeyboardText('');
  
      // 等待所有字符输入完成
      await tester.pumpAndSettle();
  
      // 验证输入的文本是否正确
      expect(enteredText, equals('input text is empty.'));
    });

    testWidgets('typeKeyboardText should handle long text', (WidgetTester tester) async {
      final textFieldKey = UniqueKey();
      String enteredText = '';
      String inputText = 'This is a very long text to test the typeKeyboardText method with multiple characters';
      
      // 为 RawKeyboardListener 和 TextField 分别创建不同的 FocusNode
      final rawKeyboardFocusNode = FocusNode();
      final textFieldFocusNode = FocusNode();
  
      // 创建一个自定义的文本输入控件，能够响应物理键盘事件
      await tester.pumpWidget(
        MaterialApp(
          home: Scaffold(
            body: KeyboardListener(
              focusNode: rawKeyboardFocusNode,
              onKeyEvent: (event) {
                if (event is KeyDownEvent) {
                  // 将键盘事件转换为文本
                  final isShiftPressed = 
                      (HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftLeft) ||
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shiftRight))|| 
                      HardwareKeyboard.instance.logicalKeysPressed.contains(LogicalKeyboardKey.shift);
                  final character = _keyToCharacter(event.logicalKey, isShiftPressed);
                  print('Key: ${event.logicalKey}, Shift: $isShiftPressed, Character: $character');
                  if (character != null) {
                    enteredText += character;
                  }
                }
              },
              child: TextField(
                key: textFieldKey,
                focusNode: textFieldFocusNode,
                // readOnly: true, // 设置为只读，因为我们通过键盘事件处理输入
                controller: TextEditingController(text: enteredText),
              ),
            ),
          ),
        ),
      );

      // 确保文本框获得焦点
      rawKeyboardFocusNode.requestFocus();
      await tester.pump();
  
      // 使用 typeKeyboardText 方法输入文本
      
      await tester.typeKeyboardText(inputText);
  
      // 等待所有字符输入完成
      await tester.pumpAndSettle();
  
      // 验证输入的文本是否正确
      expect(enteredText, equals(inputText));
    });
  });
}

